package com.ymh.git.thread.juc;

/**
 * Created by aivin on 2018/11/1.
 * 演示普通的死锁
 */
public class NormalDeadLock {

    private static Object valueFirst = new Object();//第一个锁
    private static Object valueSecond = new Object();//第二个锁


    private static void firstToSecond() {
        String threadName = Thread.currentThread().getName();
        synchronized (valueFirst) {
            System.out.println(threadName + "get First");
            SleepTools.ms(100);
            synchronized (valueSecond) {
                System.out.println(threadName + "get Second");
            }
        }

    }


    private static void secondToFirst() {
        String threadName = Thread.currentThread().getName();
        synchronized (valueSecond) {
            System.out.println(threadName + "get Second");
            SleepTools.ms(100);
            synchronized (valueFirst) {
                System.out.println(threadName + "get First");
            }
        }
    }

    private static class TestThread extends Thread {

        public TestThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            // 子线程运行时，先去拿第二个锁
            secondToFirst();
        }
    }

    public static void main(String[] args) {
        Thread.currentThread().setName("Test DeadLock");
        TestThread testThread = new TestThread("SubTestThread");
        testThread.start();
        firstToSecond(); //主线程去拿第一个锁
        //解决办法是规定所有线程去获取锁的顺序，比如，所有的线程都要先去获取第一个锁，然后才能再去获取第二个锁
    }


}
